package cn.skycity.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Description
 *  自定义认证器，主要作用就是对token进行效验，token是否过期
 *  token效验通过，则交给鉴权管理器进行鉴权
 * @Author YingBo.Dai
 * @Date 2024/10/28
 * @Version 1.0
 */
@Component
@Slf4j
public class TokenAuthenticationManager implements ReactiveAuthenticationManager {
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        return Mono.justOrEmpty(authentication).filter(auth -> auth instanceof BearerTokenAuthenticationToken)
                .cast(BearerTokenAuthenticationToken.class)
                .map(BearerTokenAuthenticationToken::getToken)
                .flatMap(token -> {
                    UsernamePasswordAuthenticationToken oAuth2Token = new UsernamePasswordAuthenticationToken("admin", "password", List.of(new SimpleGrantedAuthority("ROLE_ADMIN")));
                    return Mono.just(oAuth2Token);
                })
                .cast(Authentication.class);
    }
}
